<?php
// +----------------------------------------------------------------------
// | zhanshop-mcp / AiRewriteClient.php    [ 2025/8/11 09:30 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\provider;

use zhanshop\App;
use zhanshop\client\AichatClient;

class AiRewriteClient
{
    protected $apiHost = 'http://zhanshop-ollama:11434/v1';
    protected $apiKey = '';

    protected $aichatClient;
    public function __construct()
    {
        $this->aichatClient = new AichatClient(App::env()->get('CAHT_HOST', 'http://zhanshop-ollama:11434/v1'), App::env()->get('CAHT_KEY', ""), App::env()->get('CAHT_MODEL', 'qwen3:8b'));
    }
    public function rewrite(string $body, string $rewriteRequire = '进行风格改写，要求保留细节')
    {
        $rewriteBody = '';
        $this->aichatClient->onMessage(function ($chatClient, $msg)use (&$rewriteBody){
            echo $msg;
            $rewriteBody .= $msg;
        });
        $this->aichatClient->setQuestion($body."\r\n\r\n【将上面的内容".$rewriteRequire);
        $this->aichatClient->send();
        $bodys = explode("\n</think>\n\n", $rewriteBody);
        unset($bodys[0]);
        $rewriteBody = implode('', $bodys);
        $rewriteBody = str_replace(" ", "&nbsp;", $rewriteBody);
        $rewriteBody = str_replace("\r", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $rewriteBody);
        $rewriteBody = str_replace("\n", "<br />", $rewriteBody);
        return $rewriteBody;
    }
}